package edu.towson.cosc.cosc455.kkarolenko.markdowncompiler;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

// Compile a markdown language to html given a file
public class Compiler {
	
	public static String token;
	public static ArrayList<Token> tokens = new ArrayList<Token>();
	public static MLexicalAnalyzer lex;
	public static MSyntaxAnalyzer syn;
	public static MSemanticAnalyzer sem;
	public static String file;
	public static Node<Token> tree;

	/**
	 * @param args
	 * @throws IOException 
	 * @throws CompilerException 
	 */
	public static void main(String[] args) throws IOException, CompilerException {
		
		token = "";
		
		// 1. Check to make sure args
		// 2. Check to make sure the file has an mkd extension (endswith(".mkd")?)
		checkArgs(args);
		
		// 3. Initialization
		lex = new MLexicalAnalyzer();
		syn = new MSyntaxAnalyzer();
		sem = new MSemanticAnalyzer();
		
		file = readFile(args[0]);
		
		// 4. Call Lexical analyzer to get the first token set
		lex.getCharacter();
		lex.getNextToken();
		
		// 5. Call the start state of the parser, i.e., document();
		//		...lexer and parser does its thing
		syn.document();
		
		// 6. Call the semantic analyzer
		sem.travel(tree);
		
		// 7. Write the output file
		PrintWriter pw = new PrintWriter(args[0].substring(0, args[0].indexOf('.')) + ".html", "UTF-8");
		pw.println(sem.file);
		
		// 8. Clean up (close files, any necessary deconstructors)
		pw.close();
	}
	
	// read the file in and return a string with its contents
	public static String readFile( String file ) throws IOException {
		
		// setup
		FileReader fr = new FileReader(file);
		BufferedReader bufferedReader = new BufferedReader(fr);
		
		try {
			
			StringBuilder stringBuilder = new StringBuilder();
			String line = bufferedReader.readLine();
			
			// while there are still lines place the line and a newline char
			while (line != null) {
				stringBuilder.append(line);
				stringBuilder.append("\n");				
				line = bufferedReader.readLine();
			}
			// return the string
			return stringBuilder.toString();
		} finally {
			// close the file and reader
			bufferedReader.close();
			fr.close();
		}
		
	}
	
	// Make sure the arguments are correct
	public static void checkArgs(String[] args) throws CompilerException {
		
		// Make sure there's one argument
		if (args.length < 1) {
			throw new CompilerException("ERROR: Please supply an input markdown file.");
		}
		else if (args.length > 1) {
			throw new CompilerException("ERROR: Please supply only an input markdown file.");
		}
		
		// Make sure the input file ends in .mkd
		if (!args[0].endsWith(".mkd")) {
			throw new CompilerException("ERROR: Please supply a markdown file with the extension .mkd");
		}
	}
	
	// simplify getting the most recent token
	public static Token getLastToken() {
		return tokens.get(tokens.size()-1);
	}

}
